//
//  KMVoiceRecordHUD.swift
//  VoiceMemos
//
//  Created by Zhouqi Mo on 2/24/15.
//  Copyright (c) 2015 Zhouqi Mo. All rights reserved.
// https://github.com/SwiftStudioIst/VoiceMemos

import UIKit

@IBDesignable
class KMVoiceRecordHUD: UIView {

    @IBInspectable var rate: CGFloat = 0.0

    @IBInspectable var fillColor: UIColor = UIColor.green {
        didSet {
            setNeedsDisplay()
        }
    }

    var image: UIImage! {
        didSet {
            setNeedsDisplay()
        }
    }

    override init(frame: CGRect = .zero) {
        super.init(frame: frame)
        image = R.image.icon_mic()
        backgroundColor = .clear
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        image = R.image.icon_mic()
        backgroundColor = .clear
    }

    func update(_ rate: CGFloat) {
        self.rate = rate
        setNeedsDisplay()
    }

    override func draw(_ rect: CGRect) {
        //super.draw(rect)

        if let img = image.cgImage {
            let context = UIGraphicsGetCurrentContext()!
            context.saveGState()
            context.translateBy(x: 0, y: bounds.size.height)
            context.scaleBy(x: 1, y: -1)

            context.draw(img, in: bounds)
            context.clip(to: bounds, mask: img)

            context.setFillColor(fillColor.cgColor)
            context.fill(cgRect(x: 0, y: 0, width: bounds.width, height: bounds.height * rate))
            context.restoreGState()
        }
    }

    override func prepareForInterfaceBuilder() {
        image = R.image.icon_mic()
    }
}
